package org.springblade.modules.admin.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.ApiOperation;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.constant.BladeConstant;
import org.springblade.modules.admin.entity.MaintainSignSetingUser;
import org.springblade.modules.admin.service.IMaintainSignSetingUserService;
import org.springblade.modules.admin.service.UserSignDetailService;
import org.springblade.modules.admin.vo.DateResultVo;
import org.springblade.modules.admin.vo.HolidaysVo;
import org.springblade.modules.admin.vo.UserSignDetailPageVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/user/sign/detail")
public class UserSignDetailController {

	@Autowired
	private UserSignDetailService userSignDetailService;

	@Resource
	private RedisTemplate<String, Object> redisTemplate;

	@Resource
	private IMaintainSignSetingUserService maintainSignSetingUserService;


	@GetMapping("/bjOfTime")
	@ApiOperation("获取北京当前时间")
	public R<DateResultVo> getBeiJingTime() {
		LocalDateTime now = LocalDateTime.now(ZoneId.of("UTC+8"));
		DateResultVo dateResultVo = new DateResultVo();
		long time = Date.from(now.atZone(ZoneId.systemDefault()).toInstant()).getTime();
		dateResultVo.setTime(time);
		dateResultVo.setDate(DateUtil.format(new Date(time), "yyyyMMdd"));
		return R.data(dateResultVo);

	}

	/**
	 * 分页查询维保人员签到详情
	 *
	 * @param query
	 * @param startTime
	 * @param endTime
	 * @return
	 */
	@GetMapping("/page")
	public R<IPage<UserSignDetailPageVo>> listUserSignDetail(Query query, String startTime, String endTime, Integer signType, String types, @RequestParam(required = false) String tenantId, String userName) {
		if (StrUtil.isEmpty(tenantId)) {
			tenantId = AuthUtil.getTenantId();
		}
		if (StrUtil.isEmpty(endTime)) {
			endTime = DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss");
			startTime = DateUtil.format(DateUtil.beginOfMonth(new Date()), "yyyy-MM-dd HH:mm:ss");
		} else {
			startTime = DateUtil.format(DateUtil.parse(startTime, "yyyyMMdd"), "yyyy-MM-dd HH:mm:ss");
			endTime = DateUtil.format(DateUtil.parse(endTime, "yyyyMMdd"), "yyyy-MM-dd HH:mm:ss");
		}
		IPage<UserSignDetailPageVo> pages = userSignDetailService.listUserSignDetail(startTime, endTime, signType, types, Condition.getPage(query), tenantId, userName);
		return R.data(pages);
	}

	@PostMapping("/down/excel")
	public void downExcelDetail(HttpServletResponse response, Query query, String startTime, String endTime, Integer signType, String types, @RequestParam(required = false) String tenantId, BladeUser bladeUser, String userName) throws IOException {
		if (!bladeUser.getTenantId().equals(BladeConstant.ADMIN_TENANT_ID)) {
			tenantId = bladeUser.getTenantId();
		}
		if (StrUtil.isEmpty(endTime)) {
			endTime = DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss");
			startTime = DateUtil.format(DateUtil.beginOfMonth(new Date()), "yyyy-MM-dd HH:mm:ss");
		} else {
			startTime = DateUtil.format(DateUtil.parse(startTime, "yyyyMMdd"), "yyyy-MM-dd HH:mm:ss");
			endTime = DateUtil.format(DateUtil.parse(endTime, "yyyyMMdd"), "yyyy-MM-dd HH:mm:ss");
		}
		ExcelWriter excelWriter = null;
		ServletOutputStream outputStream = response.getOutputStream();
		try {
			List<List<String>> rows = new ArrayList<>();
			List<String> title0 = CollUtil.newArrayList("考勤记录-统计时间=" + startTime + "--" + endTime);
			List<String> title = CollUtil.newArrayList
				("考勤日期", "星期", "日期类型", "姓名", "组名称", "考勤类型", "签到时间", "签到地点", "签到状态", "签到说明", "签到补卡申请", "签退时间", "签退地点", "签退状态", "签退说明", "签退补卡申请");
			rows.add(title0);
			rows.add(title);
			userSignDetailService.downExcelDetail(startTime, endTime, signType, types, rows, tenantId, userName);
			String fileName = DateUtil.format(new Date(), "yyyyMMddHHmmss") + ".xlsx";
			setResponseHeader(response, fileName);
			excelWriter = ExcelUtil.getBigWriter(rows.size());
			excelWriter.write(rows, true);
			excelWriter.flush(outputStream, true);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (excelWriter != null) {
				excelWriter.close();
			}
			outputStream.close();
		}

	}

	/**
	 * 功能描述: 发送响应流方法
	 */
	private void setResponseHeader(HttpServletResponse response, String fileName) {
		try {
			try {
				fileName = new String(fileName.getBytes(), "ISO8859-1");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			response.setContentType("application/octet-stream;charset=ISO8859-1");
			response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
			response.addHeader("Pargam", "no-cache");
			response.addHeader("Cache-Control", "no-cache");
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	@GetMapping("/init/holiday/data")
	@ApiOperation("初始化节假日")
	public String initHolidaysData(String jsonStr) {

		jsonStr = "[{\"MonthDay\":\"0101\",\"Remark\":\"元旦\",\"Type\":\"1\"},{\"MonthDay\":\"0102\",\"Remark\":\"元旦\",\"Type\":\"1\"},{\"MonthDay\":\"0103\",\"Remark\":\"元旦\",\"Type\":\"1\"},{\"MonthDay\":\"0129\",\"Remark\":\"补班\",\"Type\":\"2\"},{\"MonthDay\":\"0130\",\"Remark\":\"补班\",\"Type\":\"2\"},{\"MonthDay\":\"0131\",\"Remark\":\"除夕\",\"Type\":\"1\"},{\"MonthDay\":\"0201\",\"Remark\":\"初一\",\"Type\":\"1\"},{\"MonthDay\":\"0202\",\"Remark\":\"初二\",\"Type\":\"1\"},{\"MonthDay\":\"0203\",\"Remark\":\"初三\",\"Type\":\"1\"},{\"MonthDay\":\"0204\",\"Remark\":\"初四\",\"Type\":\"1\"},{\"MonthDay\":\"0205\",\"Remark\":\"初五\",\"Type\":\"1\"},{\"MonthDay\":\"0206\",\"Remark\":\"初六\",\"Type\":\"1\"},{\"MonthDay\":\"0402\",\"Remark\":\"补班\",\"Type\":\"2\"},{\"MonthDay\":\"0403\",\"Remark\":\"清明节\",\"Type\":\"1\"},{\"MonthDay\":\"0404\",\"Remark\":\"清明节\",\"Type\":\"1\"},{\"MonthDay\":\"0405\",\"Remark\":\"清明节\",\"Type\":\"1\"},{\"MonthDay\":\"0424\",\"Remark\":\"补班\",\"Type\":\"2\"},{\"MonthDay\":\"0430\",\"Remark\":\"劳动节\",\"Type\":\"1\"},{\"MonthDay\":\"0501\",\"Remark\":\"劳动节\",\"Type\":\"1\"},{\"MonthDay\":\"0502\",\"Remark\":\"劳动节\",\"Type\":\"1\"},{\"MonthDay\":\"0503\",\"Remark\":\"劳动节\",\"Type\":\"1\"},{\"MonthDay\":\"0504\",\"Remark\":\"劳动节\",\"Type\":\"1\"},{\"MonthDay\":\"0507\",\"Remark\":\"补班\",\"Type\":\"2\"},{\"MonthDay\":\"0603\",\"Remark\":\"端午节\",\"Type\":\"1\"},{\"MonthDay\":\"0604\",\"Remark\":\"端午节\",\"Type\":\"1\"},{\"MonthDay\":\"0605\",\"Remark\":\"端午节\",\"Type\":\"1\"},{\"MonthDay\":\"0910\",\"Remark\":\"中秋节\",\"Type\":\"1\"},{\"MonthDay\":\"0911\",\"Remark\":\"中秋节\",\"Type\":\"1\"},{\"MonthDay\":\"0912\",\"Remark\":\"中秋节\",\"Type\":\"1\"},{\"MonthDay\":\"1001\",\"Remark\":\"国庆节\",\"Type\":\"1\"},{\"MonthDay\":\"1002\",\"Remark\":\"国庆节\",\"Type\":\"1\"},{\"MonthDay\":\"1003\",\"Remark\":\"国庆节\",\"Type\":\"1\"},{\"MonthDay\":\"1004\",\"Remark\":\"国庆节\",\"Type\":\"1\"},{\"MonthDay\":\"1005\",\"Remark\":\"国庆节\",\"Type\":\"1\"},{\"MonthDay\":\"1006\",\"Remark\":\"国庆节\",\"Type\":\"1\"},{\"MonthDay\":\"1007\",\"Remark\":\"国庆节\",\"Type\":\"1\"},{\"MonthDay\":\"1008\",\"Remark\":\"补班\",\"Type\":\"2\"},{\"MonthDay\":\"1009\",\"Remark\":\"补班\",\"Type\":\"2\"}]";
		List<HolidaysVo> voList = JSONObject.parseArray(jsonStr, HolidaysVo.class);
		redisTemplate.opsForValue().set("user:sign:date:holidays", JSONObject.toJSONString(voList));
		Object o = redisTemplate.opsForValue().get("user:sign:date:holidays");
		return Convert.toStr(o);
	}

	@GetMapping("/getUserSignStatus")
	@ApiOperation("获取用户考勤状态")
	public R<Boolean> getUserSignStatus(Long userId) {
		List<MaintainSignSetingUser> list = maintainSignSetingUserService.list(Wrappers.<MaintainSignSetingUser>lambdaQuery().eq(MaintainSignSetingUser::getUserId, userId));
		return R.data(list.size() > 0 ? true : false);
	}

	@GetMapping("/deleteUserSign")
	@ApiOperation("删除用户考勤规则")
	public R<Boolean> deleteUserSign(Long userId) {
		maintainSignSetingUserService.remove(Wrappers.<MaintainSignSetingUser>lambdaQuery().eq(MaintainSignSetingUser::getUserId, userId));
		return R.data(true);
	}


}
